package com.yt.util;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Properties;

public class PathUtil {
	/**
	 *  获取项目根路径
	 */
	public static String getProjectPath() throws IOException {
		File directory = new File("");
		String projectPath = directory.getCanonicalPath();
		return projectPath;
	}
	
	/**
	 *  获取包绝对(编译)路径,packageName为空或空字符串则获取项目(编译)绝对路径
	 */
	public static String getPackagePath(String packageName) {
		ClassLoader loader = Thread.currentThread().getContextClassLoader();
		String filePath = "";
		if (packageName != null && packageName.length() > 0)
			filePath = packageName.replace(".", "/");
		URL url = loader.getResource(filePath);
		return url.getPath();
	}

	/**
	 *  获取类的绝对(编译)路径
	 */
	public static String getClassPath(Class<?> clazz) {
		String path = "/"+getPackageName(clazz).replace('.', '/');
		return clazz.getResource(path).getFile().toString();// .getFile().toString();
	}

	/**
	 *  获取当前类所在的包
	 */
	public static String getPackageName(Class<?> clazz) {
		return clazz.getPackage().getName();
	}

	// 读取“classpath：”文件，获取输入流
	public static InputStream getClasspathInputStream(String fileName)
			throws IOException {
		if (fileName.startsWith("classpath:"))
			fileName = fileName.replaceFirst("classpath:", "").trim();
		InputStream is = PathUtil.class.getClassLoader().getResourceAsStream(fileName);
		return is;
	}
	
	public static void main(String[] args) throws IOException {
		//获取项目根路径
		System.out.println(PathUtil.getProjectPath());
		//获取项目WEB-INF路径
		System.out.println(PathUtil.getProjectPath()+"src\\main\\webapp\\WEB-INF");
		//获取com包路径（编译路径，我们的.class存放的路径）
		System.out.println(PathUtil.getPackagePath("com"));
		//获取类PathUtil的编译路径
		System.out.println(PathUtil.getClassPath(PathUtil.class));
		//获取PathUtil所在包
		System.out.println(PathUtil.getPackageName(PathUtil.class));
	}

}
